package com.patentbackend.patentmanage.service.lmpl;

import com.patentbackend.patentmanage.dto.DepartmentDTO;
import com.patentbackend.patentmanage.entity.Department;
import com.patentbackend.patentmanage.repository.DepartmentRepository;
import com.patentbackend.patentmanage.service.DepartmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

@Service
public class DepartmentServiceImpl implements DepartmentService {

    @Autowired
    private DepartmentRepository departmentRepository;

    @Override
    public Department create(DepartmentDTO departmentDTO) {
        Department department = Department.builder()
                .name(departmentDTO.getName())
                .description(departmentDTO.getDescription())
                .contactPerson(departmentDTO.getContactPerson())
                .contactPhone(departmentDTO.getContactPhone())
                .contactEmail(departmentDTO.getContactEmail())
                .introduction(departmentDTO.getIntroduction())
                .build();

        return departmentRepository.save(department);
    }

    @Override
    public Department update(Long id, DepartmentDTO departmentDTO) {
        Department department = departmentRepository.findById(id)
                .orElseThrow(() -> new RuntimeException("Department not found with id: " + id));

        if (departmentDTO.getName() != null) department.setName(departmentDTO.getName());
        if (departmentDTO.getDescription() != null) department.setDescription(departmentDTO.getDescription());
        if (departmentDTO.getContactPerson() != null) department.setContactPerson(departmentDTO.getContactPerson());
        if (departmentDTO.getContactPhone() != null) department.setContactPhone(departmentDTO.getContactPhone());
        if (departmentDTO.getContactEmail() != null) department.setContactEmail(departmentDTO.getContactEmail());
        if (departmentDTO.getIntroduction() != null) department.setIntroduction(departmentDTO.getIntroduction());

        return departmentRepository.save(department);
    }

    @Override
    public boolean existsById(Long id) {
        return departmentRepository.existsById(id);
    }

    @Override
    public Page<Department> findAll(Pageable pageable) {
        return departmentRepository.findAll(pageable);
    }

    @Override
    public List<Department> findAll() {
        return departmentRepository.findAll();
    }

    @Override
    public Optional<Department> findById(Long id) {
        return departmentRepository.findById(id);
    }

    @Override
    public void delete(Long id) {
        departmentRepository.deleteById(id);
    }
}